import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:pd_application/utils/http.dart';

class TabIndex extends StatefulWidget {
  const TabIndex({super.key});

  @override
  State<TabIndex> createState() => _TabIndexState();
}

class _TabIndexState extends State<TabIndex> {
  late String _file_name = '';
  late String _file_size = '';
  _uploadToken() async {
    // 调用上传凭证接口
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      PlatformFile fileObj = result.files.first;
      // 处理文件对象
      File file = File(fileObj.path!);
      var formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(file.path, filename: fileObj.name)
      });
      var response = HttpApi.request('/upload/upload_token', data: formData);
      print(response);
      // 更新UI

      setState(() {
        _file_name = fileObj.name;
        _file_size = fileObj.size.toString();
      });
      // 调用上传接口
    } else {
      // User canceled the picker
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '首页',
          style: TextStyle(
            color: Colors.white,
            fontSize: 20,
            fontWeight: FontWeight.bold,
            // fontStyle: FontStyle.italic,
          ),
        ),
        centerTitle: true,
        backgroundColor: Theme.of(context).primaryColor,
      ),
      body: ListView(padding: const EdgeInsets.all(20), children: [
        const TextField(
            maxLines: 10,
            decoration: InputDecoration(
              hintText: '请输入内容',
              border: OutlineInputBorder(),
            )),
        const SizedBox(height: 20),
        Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          ElevatedButton(
              onPressed: _uploadToken, child: const Text('上传Token号')),
          Text('文件名：$_file_name'),
          Text('大小：$_file_size kb')
        ])
      ]),
    );
  }
}
